/**
 * 用户登录接口
 * 
 * 接口说明：
 * - 用于用户身份验证
 * - 登录成功后返回JWT token和用户信息
 * - 此接口不需要携带token（因为是登录接口）
 */

import { API_BASE_URL, getHeaders } from '../config'
import type { ApiResponse, LoginResponseData } from '../types/common'

/**
 * 登录请求参数类型
 */
export interface LoginRequest {
  xh: string           // 学号/工号
  password: string     // 用户密码
  authMethod: string   // 认证方式，固定为"unified"
}

/**
 * 登录接口
 * 
 * @param params 登录参数
 * @returns Promise<ApiResponse<LoginResponseData>>
 * 
 * @example
 * ```typescript
 * // 请求示例
 * const loginData = {
 *   xh: "2021001",
 *   password: "123456",
 *   authMethod: "unified"
 * }
 * 
 * try {
 *   const response = await login(loginData)
 *   console.log('登录成功:', response.data)
 *   // 登录成功后可以保存token
 *   localStorage.setItem('token', response.data.token)
 * } catch (error) {
 *   console.error('登录失败:', error)
 * }
 * ```
 * 
 * @example
 * ```typescript
 * // 实际API响应格式
 * {
 *   "code": 200,
 *   "msg": "登录成功",
 *   "token": "eyJhbGciOiJIUzUxMiJ9...",
 *   "user": {
 *     "id": 233,
 *     "name": "李顺梅44",
 *     "unifiedUsername": "李顺梅44",
 *     "phone": "16600010007",
 *     "studentId": "233",
 *     "avatar": "",
 *     "cardNumber": null,
 *     "department": null,
 *     "grade": null
 *   }
 * }
 * 
 * // 转换为标准格式后
 * {
 *   "success": true,
 *   "code": 200,
 *   "message": "登录成功",
 *   "msg": "登录成功",
 *   "data": {
 *     "token": "eyJhbGciOiJIUzUxMiJ9...",
 *     "user": {
 *       "id": 233,
 *       "name": "李顺梅44",
 *       "unifiedUsername": "李顺梅44",
 *       "phone": "16600010007",
 *       "studentId": "233"
 *     }
 *   }
 * }
 * ```
 * 
 * @example
 * ```typescript
 * // 失败响应示例
 * {
 *   "code": 401,
 *   "msg": "用户名或密码错误"
 * }
 * ```
 */
export const login = async (params: LoginRequest): Promise<ApiResponse<LoginResponseData>> => {
  try {
    // 登录接口不需要携带token，所以使用基础headers
    const headers = {
      'Content-Type': 'application/json',
    }

    const response = await fetch(`${API_BASE_URL}/api/auth/login`, {
      method: 'POST',
      headers,
      body: JSON.stringify(params),
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    
    // 检查响应格式
    if (result.code !== 200) {
      throw new Error(result.msg || '登录失败')
    }

    // 转换为标准格式
    const standardResult: ApiResponse<LoginResponseData> = {
      success: true,
      code: result.code,
      message: result.msg,
      msg: result.msg,
      data: {
        token: result.token,
        user: result.user
      }
    }

    return standardResult
  } catch (error) {
    console.error('登录接口调用失败:', error)
    throw error
  }
}

/**
 * 登出接口（可选）
 * 用于清除服务端的session或token
 * 
 * @returns Promise<ApiResponse>
 */
export const logout = async (): Promise<ApiResponse> => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/auth/logout`, {
      method: 'POST',
      headers: getHeaders(),
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result: ApiResponse = await response.json()
    return result
  } catch (error) {
    console.error('登出接口调用失败:', error)
    throw error
  }
}
